﻿using Petroleum.DB.Model;
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Petroleum.Tool
{
    public class EntityTranslate
    {
        /// 用class关键字表示约束为引用类型
        /// 用struct关键字表示约束为值类型
        /// new()默认构造函数约束：如果需要在泛型类型内部实例化类型参数的对象，
        ///就必须对类型参数加以默认构造函数约束，除此之外别无选择。
        //执行查询返回对象集合 
        public static List<TEntity> Translate<TEntity>(SQLiteDataReader reader) where TEntity : class, new()
        {
            List<TEntity> list = new List<TEntity>();
            Type entityType = typeof(TEntity);
            //创建实例
            object entity = Activator.CreateInstance(entityType);
            List<string> attributes = new List<string>();
            Dictionary<string, PropertyInfo> dic = new Dictionary<string, PropertyInfo>();
            foreach (PropertyInfo info in entityType.GetProperties())
            {
                dic.Add(info.Name, info);
            }
            string columnName = string.Empty;
            //object[] attributes = info.GetCustomAttributes(true);
            if (reader != null)
            {
                while (reader.Read())
                {
                    TEntity t = new TEntity();
                    foreach (KeyValuePair<string, PropertyInfo> attribute in dic)
                    {
                        columnName = attribute.Key;
                        int filedIndex = 0;
                        while (filedIndex < reader.FieldCount)
                        {

                            if (reader.GetName(filedIndex) == columnName)
                            {
                                attribute.Value.SetValue(t, reader[filedIndex], null);
                                break;

                            }
                            filedIndex++;


                        }
                    }
                    list.Add(t);

                }
            }
            return list;

        }
      
    }
}
